package com.example.gybicycle.common.util;


import  com.alibaba.fastjson.JSON;
import  com.alibaba.fastjson.JSONObject;
import com.example.gybicycle.common.entity.Result;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeixinUtil {
    //     获取openid
    public  static String oauth2GetOpenid(String appid, String appsecret, String code) {
        String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
        String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
        HttpClient client = null;
        Map<String,Object> result =new HashMap<String,Object>();
        String msg="";
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
//                        JSONObject OpenidJSONO=JSONObject.fromObject(response);
            JSONObject OpenidJSONO=JSON.parseObject(response);
            String openid =String.valueOf(OpenidJSONO.get("openid"));
            String errmsg=String.valueOf(OpenidJSONO.get("errmsg"));

            if(openid!=null){

              /*  String token=getAccessToken(appid,appsecret);
                if(token!=null){
                    var info=getInfo(token,openid);
                    System.out.println(info);
                }*/
                return openid;
            }else {
                msg=errmsg;
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg=e.getMessage();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return null;
    }
    public static String getAccessToken(String appid, String appsecret) {
        String tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        String requestUrl = tokenurl.replace("APPID", appid).replace("APPSECRET", appsecret);
        HttpClient client = null;
        Map<String, String> result = new HashMap<String, String>();
        String accessToken = null;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.parseObject(response);
            accessToken = String.valueOf(OpenidJSONO.get("access_token"));
            return  accessToken;
//            result.put("accessToken", accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return null;
    }


    public static Map<String, String> getInfo(String access_token, String openid) {
        String infourl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

        String requestUrl = infourl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
        HttpClient client = null;
        Map<String, String> result = new HashMap<String, String>();
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.parseObject(response);
            String subscribe = String.valueOf(OpenidJSONO.get("subscribe"));
            String nickname = new String(String.valueOf(OpenidJSONO.get("nickname")).getBytes("ISO8859-1"),"UTF-8");
            String sex = String.valueOf(OpenidJSONO.get("sex"));
            String language = String.valueOf(OpenidJSONO.get("language"));
            String city = new String(String.valueOf(OpenidJSONO.get("city")).getBytes("ISO8859-1"),"UTF-8");
            String province = new String(String.valueOf(OpenidJSONO.get("province")).getBytes("ISO8859-1"),"UTF-8");
            String country = new String(String.valueOf(OpenidJSONO.get("country")).getBytes("ISO8859-1"),"UTF-8");
            String headimgurl = String.valueOf(OpenidJSONO.get("headimgurl"));
            String subscribeTime = String.valueOf(OpenidJSONO.get("subscribe_time"));
            String unionid = String.valueOf(OpenidJSONO.get("unionid"));
            result.put("subscribe", subscribe);
            result.put("nickname", nickname);
            result.put("sex", sex);
            result.put("language", language);
            result.put("city", city);
            result.put("province", province);
            result.put("country", country);
            result.put("headimgurl", headimgurl);
            result.put("subscribeTime", subscribeTime);
            result.put("unionid", unionid);

//            System.out.println(accessToken+"==================="+unionid);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return result;
    }

    public static String getTelPhone(String access_token, String code) {
        String infourl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token;
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", code);
            String reqJsonStr = JsonUtil.objToString(jsonObject);
            JSONObject wxJson = JSON.parseObject(HttpClientSslUtils.doPost(infourl, reqJsonStr));
            JSONObject  phone_info=wxJson.getJSONObject("phone_info");
            if(phone_info!=null){
                String phone=phone_info.getString("phoneNumber");
                return phone;
            }
        }catch (Exception e){

        }finally {

            // 关闭客户端

        }
        // 执行Post请求


//        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("code", code);
       /* HttpClient client = null;
        List<NameValuePair> params=new ArrayList<>();
        params.add(new BasicNameValuePair("code",code));
        try {
            HttpPost post=new HttpPost(infourl);
            HttpEntity entity=new UrlEncodedFormEntity(params,"utf-8");
            post.setEntity(entity);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(post, responseHandler);
            System.out.println(response);
            JSONObject reObj = JSONObject.parseObject(response);
            JSONObject phone_info=reObj.getJSONObject("phone_info");
            if(phone_info!=null){
                var phone=phone_info.get("phoneNumber");
                if(phone==null)
                    return null;
                return String.valueOf(phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }*/
        return null;
    }


    public static String getTelPhone(String appid, String appsecret,String code){
        String token=getAccessToken(appid,appsecret);
        if(token==null)
            return "";
        return getTelPhone(token,code);
    }



}
